﻿using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System.Security.Cryptography;
using System.Text;

namespace IMServer.Models
{
    public class User
    {
        [BsonId]
        public ObjectId Id { get; set; }

        [BsonElement("userId")]
        public string UserId { get; set; } = null!;

        public string UserName { get; set; } = null!;

        public string Password { get; set; } = null!;

        public string Avatar { get; set; } = "https://im-net.oss-cn-wuhan-lr.aliyuncs.com/default.png";

        [BsonElement("friends")]
        public string[] Friends { get; set; } = Array.Empty<string>();

        [BsonElement("groups")]
        public string[] Groups { get; set; } = Array.Empty<string>();

        // 添加一个方法生成10位全局唯一ID 
        // TODO: 改进ID生成算法
        public void GenerateUniqueId()
        {
            if (UserId == null)
            {
                string timestamp = DateTime.UtcNow.Ticks.ToString().Substring(8, 6); // 获取时间戳的后6位
                string randomNum = new Random().Next(10000, 100000).ToString().Substring(1, 4); // 4位随机数
                this.UserId = timestamp + randomNum; // 合并成10位数字字符串
            }
        }
       
        // 计算密码的 SHA256 哈希值
        public string ComputeSha256Hash(string password)
        {
            using (SHA256 sha256 = SHA256.Create())
            {
                byte[] bytes = Encoding.UTF8.GetBytes(password);
                byte[] hashBytes = sha256.ComputeHash(bytes);

                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    _ = builder.Append(hashBytes[i].ToString("x2"));
                }
                return builder.ToString();
            }
        }
        
        public bool ValidatePassword(string password)
        {
            return Password == ComputeSha256Hash(password);
        }

        // 获取用户的好友ID列表
        public string[] GetFriends()
        {
            return Friends;
        }

        // 获取用户所在的群组ID列表
        public string[] GetGroups()
        {
            return Groups;
        }
    }
}
